package com.mall507.fivepeaks.activity.community;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.AbsRecyclerViewUI;
import com.hzh.frame.widget.xrecyclerview.RecyclerViewHolder;
import com.mall507.comn.model.Message;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.widget.Banner.BGABanner;
import com.mall507.fivepeaks.widget.imageview.CircleImageView;
import com.mall507.fivepeaks.widget.imageview.ExpandImageView;
import com.mall507.fivepeaks.widget.xdialog.XAddressDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@Route(path = "/community/CommunityBusinessStoreInfoRUI")
public class CommunityBusinessStoreInfoRUI extends AbsRecyclerViewUI<Message> {
    private View headView;
    private List<String> listUrl;
    @ViewInject(R.id.collection) //收藏
    LinearLayout collection;
    @ViewInject(R.id.img_collection) //收藏图片
    ImageView img_collection;
    @ViewInject(R.id.lickNumber)
    TextView lickNumber;
    @ViewInject(R.id.send) //发送评论
    TextView send;
    @ViewInject(R.id.comment) //评论内容
    EditText comment;

    private int page = 0;
    TextView dianhua;
    TextView shijian;
    TextView dizhi;
    private int flag = 0;
    private int flag2 = 0;
    private int flag3 = 0;
    String businessAddress = "";
    String businesslat = "";
    String businesslng = "";
    
    @Override
    protected int setLayoutId() {
        return R.layout.ui_rv_businessstore_info;
    }

    @Override
    protected int setItemLayoutId(int viewType) {
        return R.layout.item_rv_businessstore_info;
    }

    @Override
    protected JSONObject setHttpParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    @Override
    protected String setHttpPath() {
        return "Comment/getBizComment";
    }

    @Override
    protected void bindView() {
        showLoding();
        getTitleView().setContent("详情");
        lickNumber.setText(getIntent().getStringExtra("collection_count"));
        headView = getLayoutInflater().inflate(R.layout.head_rv_businessstore_info, null);
        getAdapter().setHeaderView(headView);
        dianhua = headView.findViewById(R.id.phone);
        shijian = headView.findViewById(R.id.time);
        dizhi = headView.findViewById(R.id.address);
        dianhua.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                call(dianhua.getText().toString().trim());
            }
        });
        shijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag2 == 0){
                    shijian.setMaxLines(100);
                    flag2 = 1;
                } else if (flag2 == 1) {
                    shijian.setMaxLines(1);
                    flag2 = 0;
                }
            }
        });
        dizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XAddressDialog().show(CommunityBusinessStoreInfoRUI.this, businessAddress, businesslng,businesslat,new XAddressDialog.XUserMainSignRewardDialogCallBack() {
                    @Override
                    public void confirm() {
                        
                    }

                    @Override
                    public void cancel() {

                    }
                });
            }
        });
        getComment();
        views();
        isCollection();
        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserTools.getInstance().getIsLogin()){
                    if (page == 0){
                        setCollection();
                    }else if (page == 1){
                        cancelCollection();
                    }
                }else {
                    alert("请登录之后尝试");
                    ARouter.getInstance().build("/login/login").navigation();
                }
            }
        });

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserTools.getInstance().getIsLogin()){
                    if (TextUtils.isEmpty(comment.getText())){
                        alert("评论不能为空");
                    }else {
                        sendComment();
                    }
                }else {
                    alert("请登录之后尝试");
                    ARouter.getInstance().build("/login/login").navigation();
                }
            }
        });
    }

    @Override
    protected List<Message> handleHttpData(JSONObject response) {
        List<Message> list = new ArrayList<>();
        if (200 == response.optInt("code")) {
            JSONArray jsonArray = response.optJSONArray("data");
            if (jsonArray != null && jsonArray.length() > 0){
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.optJSONObject(i);
                    JSONObject member = jsonArray.optJSONObject(i).optJSONObject("member");
                    Message model = new Message();
                    if (member != null && member.length()>0){
                        model.setHead_img(member.optString("head_img"));
                        model.setNickname(member.optString("nickname"));
                    }
                    model.setContent(object.optString("content"));
                    model.setCreate_at(object.optString("create_at"));
                    list.add(model);
                }
            }
        }
        dismissLoding();
        return list;
    }

    private void getComment() {
        JSONObject params = new JSONObject();
        try {
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query("Business/getBusiness", params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")){
                    JSONObject data = response.optJSONObject("data");
                    getTitleView().setContent(data.optString("compname"));
                    ((TextView)headView.findViewById(R.id.phone)).setText(data.optString("comptel")); //店铺名称
                    ((TextView)headView.findViewById(R.id.time)).setText("营业时间：" + data.optString("hours")); //店铺营业时间
                    ((TextView)headView.findViewById(R.id.address)).setText(data.optString("compaddress")); //店铺地址
                    businessAddress = data.optString("compaddress"); //地址
                    ((TextView)headView.findViewById(R.id.content)).setText(data.optString("intro")); //店铺特色
                    ((TextView)headView.findViewById(R.id.tese)).setText("店铺特色"); //店铺特色
                    lickNumber.setText(data.optString("collection_count")); //文章收藏数量
                    businesslat = data.optString("lat"); //纬度
                    businesslng = data.optString("lng"); //经度
                    JSONArray pics = data.optJSONArray("pics");
                    if (pics != null && pics.length() > 0) {
                        listUrl = new ArrayList<>();
                        for (int i = 0; i < pics.length(); i++) {
                            listUrl.add(pics.optString(i));
                        }
                    }
                    dismissLoding();
                    bindTopBannerData(listUrl);
                }
            }
        });
    }

    //banner数据绑定
    private void bindTopBannerData(List<String> listUrl) {
        BGABanner banner = headView.findViewById(R.id.head_banner);
        banner.setAdapter(new BGABanner.Adapter<View, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, String url, int position) {
                SimpleDraweeView simpleDraweeView = itemView.findViewById(R.id.sdv_item_fresco_content);
                simpleDraweeView.setImageURI(url);
            }
        });
        banner.setData(R.layout.homerecycle_top_banner_content, listUrl, null);
    }

    @Override
    protected void bindItemData(RecyclerViewHolder holder, int position, Message model) {
        holder.setText(R.id.name, model.getNickname());
        holder.setText(R.id.desc, model.getContent());
        holder.setText(R.id.time, model.getCreate_at());
        ((CircleImageView) holder.getView(R.id.icon)).setImageURI(model.getHead_img());
    }

    private void views(){
        BaseHttp.getInstance().query("Action/viewBlog", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                super.onSuccess(response);
            }
        });
    }

    private void isCollection(){
        BaseHttp.getInstance().query("Action/isCollection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("data") == 1){
                    page = 1;
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_blue));
                }else {
                    page = 0;
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_hui));
                }
                super.onSuccess(response);
            }
        });
    }

    private void setCollection(){
        BaseHttp.getInstance().query("Action/collection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")){
                    collectionput();
                }else {
                    alert(response.optString("msg"));
                }
                super.onSuccess(response);
            }
        });
    }

    private void cancelCollection(){
        BaseHttp.getInstance().query("Action/cancelCollection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")){
                    collectionput();
                }else {
                    alert(response.optString("msg"));
                }
                super.onSuccess(response);
            }
        });
    }

    private JSONObject getParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("type", getIntent().getStringExtra("type"));
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    private void sendComment(){
        JSONObject params = new JSONObject();
        try {
            params.put("type", getIntent().getStringExtra("type"));
            params.put("id", getIntent().getStringExtra("id"));
            params.put("content", comment.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query("comment/subProductComment", params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")){
                    comment.getText().clear();
                    onRefresh();
                    alert(response.optString("msg"));
                }else {
                    alert(response.optString("msg"));
                }
                super.onSuccess(response);
            }
        });
    }

    private void collectionput(){
        final int collection_count = Integer.parseInt(lickNumber.getText().toString());
        img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_blue));
        if (page == 0){
            lickNumber.setText(String.valueOf(collection_count + 1));
            page = 1;
        }else if (page == 1){
            img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_hui));
            lickNumber.setText(String.valueOf(collection_count - 1));
            page = 0;
        }
    }
    
    private void call(String phoneNum){
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }


    /**
     * 检测程序是否安装
     *
     * @param packageName
     * @return
     */
    private boolean isInstalled(String packageName) {
        PackageManager manager = CommunityBusinessStoreInfoRUI.this.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

    /**
     * 跳转百度地图
     */
    private void goToBaiduMap() {
        if (!isInstalled("com.baidu.BaiduMap")) {
//            T.show(CommunityBusinessStoreInfoRUI.this, "请先安装百度地图客户端");
            alert("请先安装百度地图客户端");
            return;
        }
        try {
            Intent i1 = new Intent();
            i1.setData(Uri.parse("baidumap://map/geocoder?src=openApiDemo&address=" + "重庆北广场"));
            startActivity(i1);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Intent intent = new Intent();
//        intent.setData(Uri.parse("baidumap://map/direction?destination=latlng:" + mLat + "," + mLng + "|name:" + mAddressStr + // 终点
//                "&mode=driving" + // 导航路线方式
//                "&src=" + getPackageName()));
//        startActivity(intent); // 启动调用
    }
    
    /**
     * 跳转高德地图
     */
    private void goToGaodeMap() {
        if (!isInstalled("com.autonavi.minimap")) {
//            T.show(mContext, "请先安装高德地图客户端");
            alert("请先安装高德地图客户端");
            return;
        }
        try {
            String act = "android.intent.action.VIEW";
            String dat = "androidamap://keywordNavi?sourceApplication=softname&keyword=" + businessAddress + " &style=2";
            String pkg = "com.autonavi.minimap";
            Intent intent = new Intent(act, Uri.parse(dat));
            intent.setPackage(pkg);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        LatLng endPoint = BD2GCJ(new LatLng(mLat, mLng));//坐标转换
//        StringBuffer stringBuffer = new StringBuffer("androidamap://navi?sourceApplication=").append("amap");
//        stringBuffer.append("&lat=").append(endPoint.latitude)
//                .append("&lon=").append(endPoint.longitude).append("&keywords=" + mAddressStr)
//                .append("&dev=").append(0)
//                .append("&style=").append(2);
//        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
//        intent.setPackage("com.autonavi.minimap");
//        startActivity(intent);
    }
    
    /**
     * 跳转腾讯地图
     */
    private void goToTencentMap() {
        if (!isInstalled("com.tencent.map")) {
//            T.show(mContext, "请先安装腾讯地图客户端");
            alert("请先安装腾讯地图客户端");
            return;
        }
        try {
            String pathUrl = "qqmap://map/routeplan?type=drive&to=" + businessAddress + "&tocoord=" + "" + "," + "" + "&policy=2&referer=myapp";
            Intent intent = new Intent();
            intent.setData(Uri.parse(pathUrl));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        LatLng endPoint = BD2GCJ(new LatLng(mLat, mLng));//坐标转换
//        StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive")
//                .append("&tocoord=").append(endPoint.latitude).append(",").append(endPoint.longitude).append("&to=" + mAddressStr);
//        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
//        startActivity(intent);
    }
    
}
